package 尚硅谷;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zhangmin
 * @create 2022-03-23 18:57
 * 可重入锁：
 *      同一个线程外层函数获得锁后，内层递归函数任然能获得该锁---线程可以进入任何一个它已经拥有锁的同步代码块
 */
class Phone implements Runnable{
    public synchronized void sendSMS() throws Exception{
        System.out.println(Thread.currentThread().getName()+"\t invoked sendSMS()");
        sendEmail();
    }
    public synchronized void sendEmail() throws Exception{
        System.out.println(Thread.currentThread().getName()+"\t invoked sendEmail()");
    }

    Lock lock=new ReentrantLock();
    @Override
    public void run(){
        get();//只调用了get
        System.out.println(Thread.currentThread().getName()+"\t invoked sendEmail()");
    }

    public void get(){
        lock.lock();
        lock.lock();//哪怕再加一把锁也是一样的
        try {
            System.out.println(Thread.currentThread().getName()+"\t invoked get()");
            set();//在get里面调用set，get和set都加了锁的
        }finally {
            lock.unlock();
            lock.unlock();//如果这个锁不释放会出现阻塞无法执行t4
        }
    }
    public void set(){
        lock.lock();
        try {
            System.out.println(Thread.currentThread().getName()+"\t invoked set()");
        }finally {
            lock.unlock();
        }
    }
}
public class RennterLockDemo {
    public static void main(String[] args) {
        Phone phone=new Phone();
        //验证Synchronized
        new Thread(()->{
            try {
                phone.sendSMS();
            } catch (Exception e) {
                e.printStackTrace();
            }
        },"t1").start();
        new Thread(()->{
            try {
                phone.sendSMS();
            } catch (Exception e) {
                e.printStackTrace();
            }
        },"t2").start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println();
        System.out.println();
        //验证ReentrantLock
        Thread t3=new Thread(phone,"t3");
        Thread t4=new Thread(phone,"t4");
        t3.start();
        t4.start();

    }


}
